<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick } from 'vue';
import { Switch, InputNumber, Button, Spin } from 'ant-design-vue';

import { SyncOutlined, SaveOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import { useAutoTokenManager } from '#/hooks/useAutoTokenManager';
import { saveJwtConfigApi, getJwtConfigApi, reloadJwtConfigApi } from '#/api/core/sysconfig';

const {
  tokenInfo,
  loading,
  hasValidToken,
  remainingTimeText,
  autoRefreshEnabled,
  getTokenStatus,
  toggleAutoRefresh,
  manualRefresh,
  updateJwtConfig,
} = useAutoTokenManager();

const saveLoading = ref(false);
const initLoading = ref(false);
const logs = ref<Array<{ time: string; message: string; type: 'info' | 'success' | 'warning' | 'error' }>>([]);

// 添加日志
const addLog = (message: string, type: 'info' | 'success' | 'warning' | 'error' = 'info') => {
  const time = new Date().toLocaleTimeString();
  logs.value.push({ time, message, type });

  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(-50);
  }
};

// 获取时间颜色类名
const getTimeColorClass = () => {
  if (!tokenInfo.value) return 'text-gray-500';

  const remainingMs = tokenInfo.value.remainingTimeMs;
  if (remainingMs < 5 * 60 * 1000) {
    return 'text-red-500 font-bold';
  } else if (remainingMs < 15 * 60 * 1000) {
    return 'text-orange-500 font-medium';
  } else {
    return 'text-green-500';
  }
};

// 检查Token状态
const checkTokenStatus = async () => {
  addLog('🔍 手动检查Token状态...', 'info');

  const result = await getTokenStatus();
  if (result) {
    addLog(`📊 Token状态: 有效=${result.valid}, 剩余=${result.remainingTimeText}`, 'success');
  } else {
    addLog('❌ 获取Token状态失败', 'error');
  }
};

// 手动触发续期
const handleManualRefresh = async () => {
  addLog('🔄 手动触发Token续期...', 'info');

  const success = await manualRefresh();
  if (success) {
    addLog('✅ 手动续期成功', 'success');
  } else {
    addLog('❌ 手动续期失败，可能需要重新登录', 'error');
  }
};

// 配置数据（默认关闭自动续期）
const tokenSettings = reactive({
  tokenExpiry: 30,        // Token过期时间（分钟）
  renewalThreshold: 10,   // 续期阈值（分钟）
  autoRefresh: false,     // 自动续期开关，默认关闭
});

// 添加响应式调试
watch(() => tokenSettings, (newVal, oldVal) => {
  console.log('tokenSettings 变化:', {
    新值: newVal,
    旧值: oldVal
  });
}, { deep: true });

// 监听 autoRefreshEnabled 变化并同步到本地配置
watch(autoRefreshEnabled, (newValue) => {
  tokenSettings.autoRefresh = newValue;
});

// 配置项选项
const configOptions = [
  {
    key: 'autoRefresh',
    title: '自动续期',
    description: '开启自动续期会话将永不过期',
    type: 'switch',
    default: false
  }
];

// 自动续期开关事件处理
const handleAutoRefreshChange = (checked: boolean | string | number) => {
  const isEnabled = Boolean(checked);
  tokenSettings.autoRefresh = isEnabled;

  // 调用 useAutoTokenManager 的 toggleAutoRefresh 方法
  toggleAutoRefresh(isEnabled);

  // 添加日志
  addLog(
    isEnabled
      ? '🤖 已开启自动续期模式，系统将自动监控并续期Token'
      : '👤 已关闭自动续期模式，Token过期后需要重新登录',
    'info'
  );
};

// 保存配置
const saveConfig = async () => {
  try {
    saveLoading.value = true;
    addLog('💾 开始保存JWT配置...', 'info');

    // 调用后端API保存配置，包含自动续期开关
    await saveJwtConfigApi({
      tokenExpiry: tokenSettings.tokenExpiry,
      renewalThreshold: tokenSettings.renewalThreshold,
      autoRefresh: tokenSettings.autoRefresh
    });

        addLog(`✅ JWT配置保存成功: 过期时间=${tokenSettings.tokenExpiry}分钟, 续期阈值=${tokenSettings.renewalThreshold}分钟, 自动续期=${tokenSettings.autoRefresh ? '开启' : '关闭'}`, 'success');

    // 立即更新useAutoTokenManager的配置，使其生效
    updateJwtConfig({
      tokenExpiry: tokenSettings.tokenExpiry,
      renewalThreshold: tokenSettings.renewalThreshold,
      autoRefresh: tokenSettings.autoRefresh
    });

    // 调用后端重载接口，使保存的配置参数在后端生效
    try {
      addLog('🔄 正在重载后端JWT配置...', 'info');
      await reloadJwtConfigApi();
      addLog('✅ 后端JWT配置重载成功', 'success');
      message.success('配置保存成功，前后端配置已同步生效');
      await manualRefresh();
    } catch (reloadError) {
      addLog(`⚠️ 后端JWT配置重载失败: ${reloadError}`, 'warning');
      message.warning('配置已保存，但后端重载失败，请检查后端服务');
      console.error('后端JWT配置重载失败:', reloadError);
    }

  } catch (error) {
    addLog(`❌ JWT配置保存失败: ${error}`, 'error');
    message.error('配置保存失败，请重试');
    console.error('保存JWT配置失败:', error);
  } finally {
    saveLoading.value = false;
  }
};

// 加载配置
const loadConfig = async () => {
  try {
    initLoading.value = true;
    addLog('📥 正在加载JWT配置...', 'info');

    console.log('开始加载配置，当前tokenSettings:', tokenSettings);

    const config = await getJwtConfigApi();

    console.log('API返回的配置:', config);

    // 更新配置数据
    tokenSettings.tokenExpiry = config.tokenExpiry;
    tokenSettings.renewalThreshold = config.renewalThreshold;
    tokenSettings.autoRefresh = config.autoRefresh;

    // 同步到useAutoTokenManager的状态
    if (config.autoRefresh !== autoRefreshEnabled.value) {
      toggleAutoRefresh(config.autoRefresh);
    }

    // 强制触发响应式更新
    await nextTick();

    console.log('配置更新后的tokenSettings:', tokenSettings);

    addLog(`📋 JWT配置加载成功: 过期时间=${config.tokenExpiry}分钟, 续期阈值=${config.renewalThreshold}分钟, 自动续期=${config.autoRefresh ? '开启' : '关闭'}`, 'success');

    // 添加调试信息
    console.log('配置加载完成:', {
      从API获取: config,
      当前tokenSettings: tokenSettings,
      页面显示值: {
        tokenExpiry: tokenSettings.tokenExpiry,
        renewalThreshold: tokenSettings.renewalThreshold,
        autoRefresh: tokenSettings.autoRefresh
      }
    });

  } catch (error) {
    addLog(`⚠️ JWT配置加载失败，使用默认值: ${error}`, 'warning');
    console.error('加载JWT配置失败:', error);

    // 即使API失败，也要确保有默认值
    tokenSettings.tokenExpiry = 30;
    tokenSettings.renewalThreshold = 10;
    tokenSettings.autoRefresh = false;

    console.log('使用默认配置:', tokenSettings);
  } finally {
    initLoading.value = false;
  }
};

// 页面初始化
onMounted(async () => {
  addLog('🎉 智能Token管理系统已启动', 'success');
  addLog('💡 正在加载配置...', 'info');

  console.log('页面初始化 - 初始tokenSettings:', tokenSettings);

  // 加载配置（会自动设置自动续期状态）
  await loadConfig();

  console.log('页面初始化完成 - 最终tokenSettings:', tokenSettings);

  // 🔥 初始化时检查Token状态，确保页面正常显示状态信息
  addLog('🔍 初始化检查Token状态...', 'info');
  await checkTokenStatus();
});
</script>

<template>
  <div class="jwt-config-container">
    <!-- Token设置 Block -->
    <Spin :spinning="initLoading" tip="正在加载配置...">
      <div class="config-block">

      <!-- 过期时间设置 -->
      <div class="number-item">
        <div class="number-content">
          <span class="number-label">过期时间</span>
          <span class="number-description">Token过期时间（分）</span>
        </div>
        <InputNumber
          v-model:value="tokenSettings.tokenExpiry"
          :min="5"
          :max="480"
          :step="5"
          size="small"
          style="width: 60px"
          :controls="true"
          :disabled="tokenSettings.autoRefresh"
        />
      </div>

      <!-- 续期阈值设置 -->
      <div class="number-item">
        <div class="number-content">
          <span class="number-label">续期阈值</span>
          <span class="number-description">提前续期时间阈值（分）</span>
        </div>
        <InputNumber
          v-model:value="tokenSettings.renewalThreshold"
          :min="5"
          :max="15"
          :step="5"
          size="small"
          style="width: 60px"
          :controls="true"
          :disabled="tokenSettings.autoRefresh"
        />
      </div>

      <!-- 自动续期开关 -->
      <div
        v-for="option in configOptions"
        :key="option.key"
        class="switch-item"
      >
        <div class="switch-content">
          <span class="switch-label">{{ option.title }}</span>
        </div>
        <Switch
          v-model:checked="tokenSettings[option.key as keyof typeof tokenSettings]"
          size="small"
          @change="handleAutoRefreshChange"
        />
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <!-- 保存配置按钮 -->
        <Button
          type="primary"
          :loading="saveLoading"
          @click="saveConfig"
        >
          <template #icon>
            <SaveOutlined />
          </template>
          保存配置
        </Button>

        <!-- 手动续期按钮（仅在自动续期关闭时显示） -->
        <Button
          v-if="!tokenSettings.autoRefresh"
          type="default"
          :loading="loading"
          @click="handleManualRefresh"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
          手动续期
        </Button>

        <!-- Token状态检查按钮 -->
        <Button
          type="default"
          :loading="loading"
          @click="checkTokenStatus"
        >
          <template #icon>
            <SyncOutlined />
          </template>
          检查状态
        </Button>


      </div>

      <!-- Token状态显示 -->
      <div class="token-status">
        <div class="status-item">
          <span class="status-label">Token状态:</span>
          <span :class="['status-value', hasValidToken ? 'status-normal' : 'status-error']">
            {{ hasValidToken ? '有效' : '无效' }}
          </span>
        </div>

        <div class="status-item">
          <span class="status-label">剩余时间:</span>
          <span :class="['status-value', getTimeColorClass()]">
            {{ remainingTimeText }}
          </span>
        </div>

        <div class="status-item">
          <span class="status-label">续期模式:</span>
          <span :class="['status-value', tokenSettings.autoRefresh ? 'status-normal' : 'status-manual']">
            {{ tokenSettings.autoRefresh ? '自动续期' : '手动模式' }}
          </span>
        </div>

        <!-- 调试信息 -->
        <div class="status-item">
          <span class="status-label">当前配置:</span>
          <span class="status-value">
            过期时间: {{ tokenSettings.tokenExpiry }}分钟, 续期阈值: {{ tokenSettings.renewalThreshold }}分钟, 自动续期: {{ tokenSettings.autoRefresh ? '开启' : '关闭' }}
          </span>
        </div>
              </div>
      </div>
    </Spin>
  </div>
</template>

<style scoped>
.jwt-config-container {
  padding: 1.5rem 0;
  max-width: 100%;
}

.config-block {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: hsl(var(--popover));
  border-radius: 0.5rem;
  border: 1px solid hsl(var(--border));
}

.block-title {
  margin: 0 0 1rem 0;
  font-size: 1rem;
  font-weight: 600;
  color: hsl(var(--foreground));
  letter-spacing: -0.025em;
}

.config-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 0;
  border-bottom: 1px solid hsl(var(--border));
}

.config-item:last-child {
  border-bottom: none;
}

.config-label {
  font-size: 0.875rem;
  color: hsl(var(--foreground));
}

.config-value {
  font-size: 0.875rem;
  font-weight: 500;
  color: hsl(var(--primary));
}

.config-status {
  font-size: 0.875rem;
}

.status-enabled,
.status-normal {
  color: hsl(var(--success));
  font-weight: 500;
}

.status-disabled,
.status-error {
  color: hsl(var(--destructive));
  font-weight: 500;
}

.status-manual {
  color: hsl(var(--warning));
  font-weight: 500;
}

.switch-item,
.number-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 0;
  border-bottom: 1px solid hsl(var(--border));
}

.switch-item:last-child,
.number-item:last-child {
  border-bottom: none;
}

.switch-content,
.number-content {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.switch-label,
.number-label {
  font-size: 0.875rem;
  color: hsl(var(--foreground));
  margin-bottom: 0.25rem;
  font-weight: 500;
}

.switch-description,
.number-description {
  font-size: 0.75rem;
  color: hsl(var(--muted-foreground));
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 0.75rem;
  padding: 1rem 0 0.75rem 0;
  border-top: 1px solid hsl(var(--border));
  margin-top: 0.75rem;
}

/* Token状态显示区域 */
.token-status {
  padding: 1rem 0 0 0;
  border-top: 1px solid hsl(var(--border));
  margin-top: 0.75rem;
}

.status-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0;
}

.status-label {
  font-size: 0.875rem;
  color: hsl(var(--muted-foreground));
}

.status-value {
  font-size: 0.875rem;
  font-weight: 500;
}

.logs-container {
  max-height: 200px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid hsl(var(--border) / 0.5);
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  font-size: 0.75rem;
  color: hsl(var(--muted-foreground));
  min-width: 60px;
  margin-right: 0.75rem;
}

.log-type {
  margin-right: 0.75rem;
}

.log-message {
  font-size: 0.875rem;
  color: hsl(var(--foreground));
  flex: 1;
}

/* 深色主题通过CSS变量自动适配 */

/* 禁用状态样式 */
:deep(.ant-input-number-disabled) {
  background-color: hsl(var(--muted)) !important;
  color: hsl(var(--muted-foreground)) !important;
  border-color: hsl(var(--border)) !important;
  cursor: not-allowed;
}

:deep(.ant-input-number-disabled .ant-input-number-input) {
  background-color: transparent !important;
  color: hsl(var(--muted-foreground)) !important;
  cursor: not-allowed;
}

:deep(.ant-input-number-disabled .ant-input-number-handler-wrap) {
  background-color: hsl(var(--muted)) !important;
  border-color: hsl(var(--border)) !important;
}

/* 按钮样式 */
:deep(.ant-btn-primary) {
  background-color: hsl(var(--primary));
  border-color: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
}

:deep(.ant-btn-primary:hover) {
  background-color: hsl(var(--primary) / 0.9);
  border-color: hsl(var(--primary) / 0.9);
}

:deep(.ant-btn-default) {
  background-color: hsl(var(--background));
  border-color: hsl(var(--border));
  color: hsl(var(--foreground));
}

:deep(.ant-btn-default:hover) {
  background-color: hsl(var(--accent));
  border-color: hsl(var(--accent-foreground));
  color: hsl(var(--accent-foreground));
}
</style>
